import {
  Box,
  Flex,
  Select,
  SimpleGrid,
  Spinner,
  Text,
  useToast,
} from '@chakra-ui/react';
import { useEffect, useMemo, useState } from 'react';
import ProductCard from './ProductCard';
import { fetchCatalogItems, type CatalogItem } from '../../lib/api';
import { latestProducts } from '../../data/products';

const sortOptions = ['Price', 'Popularity'];

const ProductSection = () => {
  const [items, setItems] = useState<CatalogItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const toast = useToast();

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      setLoading(true);
      try {
        const data = await fetchCatalogItems();
        if (!cancelled) {
          setItems(data);
          setError(null);
        }
      } catch (err) {
        if (!cancelled) {
          const message = err instanceof Error ? err.message : 'Failed to load catalog items';
          setError(message);
          toast({
            title: '加载商品失败',
            description: '显示示例数据，稍后再试。',
            status: 'warning',
            duration: 5000,
            isClosable: true,
          });
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void load();
    return () => {
      cancelled = true;
    };
  }, [toast]);

  const displayItems = useMemo(() => {
    if (items.length > 0) {
      return items;
    }
    return latestProducts;
  }, [items]);

  return (
    <Box bg="white" border="1px solid" borderColor="gray.200" borderRadius="2xl" p={{ base: 4, md: 6 }}>
      <Flex
        bg="brand.500"
        color="white"
        px={{ base: 3, md: 4 }}
        py={3}
        borderRadius="lg"
        mb={6}
        align="center"
        justify="space-between"
        gap={3}
        direction={{ base: 'column', sm: 'row' }}
      >
        <Text fontWeight="700" textTransform="uppercase" letterSpacing="0.08em">
          ★ Last Products
        </Text>
        <Select
          size="sm"
          maxW="200px"
          bg="white"
          color="gray.800"
          borderRadius="full"
          focusBorderColor="brand.300"
          isDisabled
        >
          {sortOptions.map((option) => (
            <option key={option} value={option}>
              Sort by {option}
            </option>
          ))}
        </Select>
      </Flex>

      {loading ? (
        <Flex py={12} justify="center" align="center" direction="column" gap={3}>
          <Spinner size="lg" color="brand.500" />
          <Text color="gray.500">Loading catalog items...</Text>
        </Flex>
      ) : (
        <>
          {error && (
            <Text mb={4} color="orange.500" fontSize="sm">
              {error}（正在显示示例商品）
            </Text>
          )}
          <SimpleGrid columns={{ base: 1, sm: 2, md: 3 }} spacing={4}>
            {displayItems.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </SimpleGrid>
        </>
      )}
    </Box>
  );
};

export default ProductSection;
